﻿using ClumsyWords.Portable.Model;
using ClumsyWords.Portable.ViewModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace ClumsyWords
{
    public class LoadDataService : ILoadDataService
    {
        public async Task<List<CommonGroup<TermDefinition>>> LoadLocalDataAsync(string[] fileNames)
        {
            List<CommonGroup<TermDefinition>> groups = new List<CommonGroup<TermDefinition>>();

            foreach (var fileName in fileNames)
            {
                StorageFile file = null;
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
                //file = await ApplicationData.Current.LocalFolder.GetFileAsync(targetFileName);


                Stream inStream = await file.OpenStreamForReadAsync();

                using (StreamReader reader = new StreamReader(inStream))
                {
                    string data = await reader.ReadToEndAsync();
                    reader.Close();
                    if (data != "[]")
                    {
                        var group = await JsonConvert.DeserializeObjectAsync<CommonGroup<TermDefinition>>(data);
                        if (group.Key != String.Empty)
                            groups.Add(group);
                    }
                }
            }

            return groups;
        }

        public async Task<CommonGroup<TermDefinition>> LoadRemoteDataAsync()
        {
            throw new NotImplementedException();
            //return new CommonGroup<TermDefinition>();
        }
    }
}
